package com.ia.aistream.manager.framework.redis.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Sets;
import com.ia.aistream.manager.framework.redis.RedisSetManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Set;

@Service
public class RedisSetManagerImpl implements RedisSetManager {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void sadd(String key, Object... members) {
        if (members == null || members.length == 0) {
            return;
        }

        for (int i = 0; i < members.length; i++) {
            redisTemplate.opsForSet().add(key, JSON.toJSONString(members[i]));
        }
    }

    @Override
    public boolean smembers(String key, Object member) {
        return Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(key, JSON.toJSONString(member)));
    }

    @Override
    public <T> Set<T> smembers(String key) {
        Set<String> set = redisTemplate.opsForSet().members(key);
        if (CollectionUtils.isEmpty(set)) {
            return Sets.newLinkedHashSet();
        }

        Set<T> result = Sets.newLinkedHashSet();
        TypeReference<T> reference = new TypeReference<T>(){};
        set.forEach(menber -> result.add(JSON.parseObject(menber, reference)));
        return result;
    }

    @Override
    public void srem(String key, Object member) {
        redisTemplate.opsForSet().remove(key, JSON.toJSONString(member));
    }

    @Override
    public long scard(String key) {
        Long size = redisTemplate.opsForSet().size(key);
        return size == null ? 0 : size;
    }
}
